define([ 'angular'/*,'summernoteCN'*/,'angularSummernote'], function(angular) {
'use strict';
	angular.module('inventory.fileItemDescribe', ['summernote'])
		/*
        .controller('OptCtrl', function($scope) {
          $scope.options = {
            height: 150,
            toolbar: [
              ['style', ['bold', 'italic', 'underline', 'clear']],
              ['color', ['color']],
              ['para', ['ul', 'ol', 'paragraph']],
              ['height', ['height']]
            ]
          };
        })
        .controller('AirmodeCtrl', function($scope) {
          $scope.text = "<h3>This is an Air-mode editable area.</h3>";
          $scope.options = {
            popover: {
              image: [
                ['imagesize', ['imageSize100', 'imageSize50', 'imageSize25']],
                ['float', ['floatLeft', 'floatRight', 'floatNone']],
                ['remove', ['removeMedia']]
              ],
              link: [
                ['link', ['linkDialogShow', 'unlink']]
              ],
              air: [
                ['color', ['color']],
                ['font', ['bold', 'underline', 'clear']],
                ['para', ['ul', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']]
              ]
            }
          };
          $scope.mediaDelete = function(target) {
            console.log('media is delted:', target);
          }
        })
        */
		/*
        .controller('CodeCtrl', function($scope) {
          $scope.text = "Hello World";
          //上传图片
          $scope.imageUpload = function(files) {
              var timestamp = new Date().getTime();
              var data = new FormData();
              data.append("file", files);
              data.append("key", timestamp);
              data.append("token", $scope.uptoken);
              $.ajax({
                  data: data,
                  type: "POST",
                  url: "http://upload.qiniu.com",
                  cache: false,
                  contentType: false,
                  processData: false,
                  success: function (data) {
                      var editor = $.summernote.eventHandler.getModule();
                      editor.insertImage($scope.editable,$scope.prefix+'/'+data.key);
                  },
                  error: function () {
                      alert('上传失败')
                  }
              });
          };
          
        })
        */
		/*
        .controller('CallbacksCtrl', function($scope) {
          $scope.init = function() { console.log('Summernote is launched'); };
          $scope.enter = function() { console.log('Enter/Return key pressed'); };
          $scope.focus = function(e) { console.log('Editable area is focused'); };
          $scope.blur = function(e) { console.log('Editable area loses focus'); };
          $scope.paste = function(e) {
            console.log('Called event paste: ' +  e.originalEvent.clipboardData.getData('text'));
          };
          $scope.change = function(contents) {
            console.log('contents are changed:', contents, $scope.editable);
          };
          $scope.keyup = function(e) { console.log('Key is released:', e.keyCode); };
          $scope.keydown = function(e) { console.log('Key is pressed:', e.keyCode); };
          $scope.imageUpload = function(files) {
            console.log('image upload:', files);
            console.log('image upload\'s editor:', $scope.editor);
            console.log('image upload\'s editable:', $scope.editable);
          };
        })
        */

	.controller('fileItemDescribeCtrl',['$rootScope', '$scope', 'BizData', f])//控制器结束
	function f($rootScope, $scope, BizData) {

		var Model = this;
		
		/**
		name:bizData#onNewCreateParam
		description: <b>[回调型事件]</b>业务新增数据创建新增参数事件，可以增加和修改用户自定义的参数
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"param" : {justep.Request.ActionParam} 新增参数对象,
			"defaultValues" : array - 新增行的默认值数组 ，数组的长度决定新增行数，数组中的对象是列的默认值
				defaultValues格式：
					[
						{列名:默认值,...},
						{列名:默认值,...},
						...
					]
		}
		</xmp>	
		@see justep.XData#newData
		@see justep.Request.ActionParam
		*/
		Model.dataMasterNewCreateParam = function(event) {
			event.param = {"billType": billType};
		}
		
		Model.dataMasterAfterRefresh = function(event) {
			//打开窗口之后，至于编辑状态
			Model.edit();
		}
		

		/**
		name:bizData#onBeforeDelete
		description: <b>[回调型事件]</b>业务数据删除前
		@param {object} event 它的结构如下:<br/>
		{
			"source":组件的js对象
			,"cancel":可修改	，设置为true后中断当前delete动作
			,"deleteIDList":删除的行Id数组
		}
		*/
		Model.dataMasterBeforeDelete = function(event) {
//			alert(event.deleteIDList[0]);
		}
		/**
		name:bizData#onAfterDelete
		description: <b>[回调型事件]</b>业务数据删除后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"deleteIDList" : 删除的行Id数组
		}
		</xmp>	
		*/
		Model.dataMasterAfterDelete = function(event) {
//			alert('删除之后！')
		}



		
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"rowID" : 行Id,
			"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataMasterIndexChanged = function(event) {

		}
		
		/**
		name:bizData#onDataChanged
		description: <b>[回调型事件]</b>数据发生变化（包括新增、刷新、删除、修改引起的变化），感知从data的变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"changedSource" ：触发变化的组件的js对象，当从data触发时返回从data对象,
			"selfChanged" : 是否自身变化，false：从data触发的变化,
			"type" : 触发变化的类型，包括：new、delete、refresh、valueChanged、clear，其他参数根据触发类型不同给出不同参数，参考onAfterNew等事件参数
		}
		</xmp>	
		*/
		Model.dataMasterDataChanged = function(event) {
			
		}
		
		/**
		name:bizData#onValueChanged
		description: <b>[回调型事件]</b>数据变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象,
			"column" : 关系,
			"rowIndex" : 行索引,
			"value" : 新值,
			"originalValue" : 旧值
		}
		</xmp>	
		*/
		//输入值变化，监视input的输入，ng-change
		Model.dataMasterValueChanged = function(event) {
			
		}
		


		/**
		name:bizData#onBeforeNew
		description: <b>[回调型事件]</b>业务数据新增前
		@param {object} event 它的结构如下:<br/>{"source":组件的js对象,"cancel":可修改，设置为true后中断当前new动作}
		 */
		Model.dataMasterBeforeNew = function(event) {

		};
		/**
		 * name:bizData#onAfterNew description: <b>[回调型事件]</b>业务数据新增后
		 * 
		 * @param event
		 *            它的结构如下:<br/>{"source":组件的js对象,"id":新增的行Id}
		 */
		Model.dataMasterAfterNew = function(event){
			
		}

		Model.dataMasterBeforeSave = function(event) {
//			console.log('dataMasterBeforeSave-->',event);
		};

		Model.dataMasterAfterSave = function(event) {
			console.log('dataMasterAfterSave-->',event);
			alert('保存成功！');
		};



		Model.gridRowClick = function(event){
			
		}

		Model.gridRowDblClick = function(event){
			Model.edit();
		}
		
		
		
		
		var options = {};
		options.container = Model;
		options.concept = 'FileItem';
		options.name = 'dataMaster';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
 		options.creater = '/inventory/fileItem/list/create';
 		options.reader = '/inventory/fileItem/list/query';
		options.writer = '/inventory/fileItem/list/save';
		options.deleter = '/inventory/fileItem/list/delete';
		options.idColumnDefine = "fID";
		options.idColumnName = "fID";
		options.isTree = false;
		options.parentRelation = 'fParent';
		options.nodeKindRelation = 'nodeKind';
		options.nodeLevelRelation = 'nodeLevel';
		options.pathRelation = 'fID';
		options.directDeleteMode = true;
		options.limit = 15;
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataMasterIndexChanged;
		options.onBeforeNew = Model.dataMasterBeforeNew;
		options.onAfterNew = Model.dataMasterAfterNew;
		options.onBeforeDelete = Model.dataMasterBeforeDelete;
		options.onAfterDelete = Model.dataMasterAfterDelete;
		options.onValueChanged = Model.dataMasterValueChanged;
		options.onDataChanged = Model.dataMasterDataChanged;
		options.onAfterRefresh = Model.dataMasterAfterRefresh;
		options.onBeforeSave = Model.dataMasterBeforeSave;
		options.onAfterSave = Model.dataMasterAfterSave;
		options.onNewCreateParam = Model.dataMasterNewCreateParam;
		
		Model.dataMaster = new BizData(options);

		//监视对象中的所有变动
		Model.dataMaster.deregRows = $scope.$watch('Model.dataMaster.rows',Model.dataMaster.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////
		
		
		
		////////////////////启动执行开始///////////////////////////////////////////////////

		//修改
		Model.edit = function(){
			Model.dataMaster.editData();
		}
		 
        Model.ok = function () {  
        	Model.dataMaster.saveData();
	    };  
	    
	    //富文本编辑器
        ///////////////////////////////////////////////////////////////////////////////
        $scope.init = function() { console.log('Summernote is launched'); };
        $scope.enter = function() { console.log('Enter/Return key pressed'); };
        $scope.focus = function(e) { console.log('Editable area is focused'); };
        $scope.blur = function(e) { console.log('Editable area loses focus'); };
        $scope.paste = function(e) {
          console.log('Called event paste: ' +  e.originalEvent.clipboardData.getData('text'));
        };
        $scope.change = function(contents) {
          console.log('contents are changed:', contents, $scope.editable);
        };
        $scope.keyup = function(e) { console.log('Key is released:', e.keyCode); };
        $scope.keydown = function(e) { console.log('Key is pressed:', e.keyCode); };
//        $scope.imageUpload = function(files) {
//          console.log('image upload:', files);
//          console.log('image upload\'s editor:', $scope.editor);
//          console.log('image upload\'s editable:', $scope.editable);
//        };

        
        //上传图片
	    $scope.imageUpload = function(files) {
        	/*
            var timestamp = new Date().getTime();
            var data = new FormData();
            data.append("file", files[0]);
            data.append("key", timestamp);
            data.append("token", $scope.uptoken);
            $.ajax({
                data: data,
                type: "POST",
                //url: "http://upload.qiniu.com111",
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                	console.log('imageUpload.data-->>',data);
                    var editor = $.summernote.eventHandler.getModule();
                    editor.insertImage($scope.editable,$scope.prefix+'/'+data.key);
                },
                error: function () {
                    alert('上传失败')
                }
            });
            */
        	
            var editor = $scope.editor;
            //console.log('image upload:', files);
            //console.log('image upload\'s editor:', $scope.editor);
            //console.log('image upload\'s editable:', $scope.editable);
            var fWidth = 0;
            var fHeight = 0;

            var timestamp = new Date().getTime();
            var data = new FormData();
            data.append("file", files[0]);
            data.append("key", timestamp);
            //data.append("token", $scope.uptoken);
            
            //console.log('data-->',data);
            data.append("lastModified", files[0].lastModified);
            data.append("fileScale", fWidth+'X'+fHeight);
            data.append("destDir", "");

            $.ajax({
                data: data,
                type: "POST",
                //url: "http://upload.qiniu.com111",
                url: $rootScope.getProjectName() + '/baseinfo/fastdfsFiles/list/upload', //配置的上传图片的路由
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                	console.log('imageUpload.data-->>',data);
                	if(data.code==0){
                    	var url = data.data.serverName + "/" + data.data.groupName + "/" + data.data.remoteFileName;
                        //var editor = $.summernote.eventHandler.getModule();
                    	//editor.insertImage($scope.editable ,url, data.originalFilename);
                    	
                    	$scope.editor.summernote('insertImage', url/*, data.originalFilename*/);
                    	/*
                    	$scope.editor.summernote('insertImage', url, function ($image) {
                    		  $image.css('width', $image.width() / 3);
                    		  $image.attr('data-filename', 'retriever');
                    		});
                    	*/
                	}else{
                		alert('上传失败！');
                	}
                }
            });
            
        };
        
        //图片删除
        $scope.mediaDelete = function (target){
        	console.log('target-->>',target);
            var src = target.attrs.src;
         	console.log('src-->>',src);
//          httpService.formPost("file/deleteEditorImageBySRC",{src:src})
//              .success(function(data){
//          });

            $.ajax({
                type: "POST",
                url: $rootScope.getProjectName() + '/baseinfo/fastdfsFiles/list/deleteBySrc', 
                data: JSON.stringify({"src":src}),
	            contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                	console.log('mediaDelete.data-->>',data);
                	if(data.code==0){
                		alert('删除成功');
                	}else{
                		alert('删除失败');
                	}
                	
                }
            });

         };
       
        //预览功能
        $scope.preview = function (editItem) {
            ngDialog.open({
                width: 1000,
                template: 'articleDetail',
                className: 'ngdialog-theme-default',
                scope: $scope,
                controller:['$scope','$sce', function ($dlgScope,$sce) {
                    $dlgScope.previewItem = editItem;
                    $scope.trustArticleContent = $sce.trustAsHtml(editItem.content);
                      }]
                  });
              };
        ///////////////////////////////////////////////////////////////////////////////
         
   
		//接收调用的参数

		Model.winParams = $rootScope.winParams;
		console.log('Model.winParams-->>',Model.winParams);
		Model.dataMaster.id = Model.winParams.id;
	    Model.dataMaster.refreshData();
		
	    return Model;

	}	
	
});//define结束
	
